# /lab_booking/routers/reservations.py

from typing import List, Union
from datetime import date
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
# --- 导入项目内部模块 ---
from lab_booking import crud, models, schemas
from lab_booking.database import get_db
from lab_booking.routers.auth import get_current_user

# --- 创建路由器实例 ---
router = APIRouter(
    prefix="/reservations",  # 所有本模块的 API 路径都以 /reservations 开头
    tags=["预约与订单管理 (Reservations & Orders)"]
)

# ==========================================================
# === 核心 API 接口定义 ===
# ==========================================================



# --- 获取“预约订单”列表的专用接口 ---
@router.get("/me/bookings", response_model=List[schemas.ReservationDetail])
def read_my_booking_list(
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """【需登录】获取“预约订单”页面的列表 (待使用, 进行中, 已取消, 已超时)"""
    return crud.get_user_reservations_for_booking_list(db, user_id=current_user.id)


# --- 获取“进行中”列表的专用接口 ---
@router.get("/me/ongoing", response_model=List[schemas.OngoingReservation])
def read_my_ongoing_list(
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """【需登录】获取“进行中”页面的列表"""
    return crud.get_ongoing_usages(db, user_id=current_user.id)


# --- 获取“全部订单(历史)”列表的专用接口 ---
@router.get("/me/history", response_model=List[schemas.HistoryUsageRecord])
def read_my_history_list(
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """【需登录】获取“全部订单”页面的列表 (已完成的)"""
    return crud.get_history_usages(db, user_id=current_user.id)


@router.post("/new", response_model=schemas.ReservationInfo)
def create_new_reservation(
    reservation: schemas.ReservationCreate, 
    db: Session = Depends(get_db),
    current_user: models.User = Depends(get_current_user) # 保护此接口
):
    """【需登录】创建一条新的设备预约记录。"""
    db_reservation = crud.create_reservation(
        db=db, 
        reservation=reservation, 
        creator_user_id=current_user.id
    )
    if db_reservation is None:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Conflict: The selected time slot is already booked.")
    return db_reservation


@router.patch("/{reservation_id}/cancel", status_code=status.HTTP_204_NO_CONTENT)
def cancel_my_reservation(
    reservation_id: int,
    current_user: models.User = Depends(get_current_user), # 保护此接口
    db: Session = Depends(get_db)
):
    """【需登录】用户取消一条“待使用”的预约。"""
    result = crud.cancel_reservation(db, reservation_id=reservation_id, user_id=current_user.id)
    if not result:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Reservation not found or cannot be cancelled.")
    # 成功时，FastAPI 会自动返回 204 No Content 状态码
    return


@router.post("/{reservation_id}/start", response_model=schemas.UsageRecordStart)
def start_using_device(
    reservation_id: int,
    current_user: models.User = Depends(get_current_user), # 保护此接口
    db: Session = Depends(get_db)
):
    """【需登录】“去使用”操作，将预约转为进行中状态，并创建使用记录。"""
    result = crud.start_usage(db, reservation_id=reservation_id, user_id=current_user.id)
    if result is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Reservation not found or not in correct status.")
    if result == "already_started":
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Usage has already started for this reservation.")
    return result


@router.patch("/usage/{usage_record_id}/end", response_model=schemas.HistoryUsageRecord)
def end_using_device(
    usage_record_id: int,
    usage_data: schemas.UsageRecordEnd,
    current_user: models.User = Depends(get_current_user), # 保护此接口
    db: Session = Depends(get_db)
):
    """【需登录】“结束使用”操作，并提交最终的实际使用信息。"""
    result = crud.end_usage(db, usage_record_id=usage_record_id, usage_data=usage_data, user_id=current_user.id)
    if result is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Usage record not found or already ended.")
    return result




@router.get("/usage/{usage_record_id}/details", response_model=schemas.HistoryUsageRecord)
def read_usage_record_details(
    usage_record_id: int,
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """【需登录】获取单个已完成订单的详细信息"""
    db_usage_record = crud.get_usage_record_details(db, usage_record_id=usage_record_id, user_id=current_user.id)
    if db_usage_record is None:
        raise HTTPException(status_code=404, detail="Usage record not found.")
    return db_usage_record


@router.get("/{device_id}/by-date", response_model=List[schemas.ReservationInfo])
def read_device_reservations_on_date(
    device_id: int, 
    reservation_date: date, 
    db: Session = Depends(get_db)
):
    """【无需登录】获取指定设备在特定日期的所有有效预约（用于详情页时间选择）。"""
    return crud.get_reservations_by_device_and_date(
        db, device_id=device_id, target_date=reservation_date
    )